package com.cn.zpark;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * @PackageName: com.cn.zpark
 * @ClassName: JdbcBatchInsert
 * @Description:JDBC批量处理sql语句, 批量插入数据
 * @author: RZS
 * @date: 2022/3/30  19:02
 */
public class JdbcBatchInsert {
    public static void main(String[] args) {
        // 准备数据库连接信息
        String url = "jdbc:mysql://192.168.83.128:3306/java_web022?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
        String user = "root";
        String pwd = "root";

        Connection conn = null;
        Statement stat = null;

        try {
            // 1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获取数据库连接对象
            conn = DriverManager.getConnection(url, user, pwd);
            // 3、创建sql语句
            String sql1 = "insert into tab1(uname) values('李四')";
            String sql2 = "insert into tab1(uname) values('王麻子')";
            String sql3 = "insert into tab1(uname) values('赵六')";
            String sql4 = "insert into tab1(uname) values('钱七')";
            // 4、创建statement对象
            stat = conn.createStatement();
            // 5、添加sql到批处理程序中
            stat.addBatch(sql1);
            stat.addBatch(sql2);
            stat.addBatch(sql3);
            stat.addBatch(sql4);
            // 6、执行批处理sql语句
            int rows[] = stat.executeBatch();
            System.out.println("批量执行sql成功：" + rows.length);

        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            // 7、关闭资源
            try {
                // 断言
                assert stat != null;
                stat.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }



    }
}
